//
//  NRWFindPassWordVC.m
//  New_Runway
//
//  Created by 邢毅 on 2018/5/3.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "NRWFindPassWordVC.h"

typedef NS_ENUM(NSUInteger, TextFieldTag) {
    kPhoneNumTextFieldTag = 10,
    kCodeTextFieldTag = 20,
    kNewPassWordTextFieldTag = 30,
    kSecondPassWordTextFieldTag = 40
};

@interface NRWFindPassWordVC ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topMarginConstraint;

@property (weak, nonatomic) IBOutlet UITextField *phoneNumTextField;

@property (weak, nonatomic) IBOutlet UITextField *codeTextField;

@property (weak, nonatomic) IBOutlet UIButton *getCodeBtn;

@property (weak, nonatomic) IBOutlet UITextField *passWordTextField;

@property (weak, nonatomic) IBOutlet UITextField *secondPassWordTextField;

@property (strong, nonatomic) NSTimer *timer;

@property (weak, nonatomic) IBOutlet UIButton *completedBtn;

@end

@implementation NRWFindPassWordVC
{
    NSInteger _timeLeft;
}

#pragma mark - lifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    _timeLeft = 60;
    
    self.completedBtn.enabled = NO;
    
    [self setupNavigation];
 
    [self setupUI];
    
}

- (void)viewDidDisappear:(BOOL)animated {
    
    [super viewDidDisappear:animated];
    
    [self removeTimer];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - UI
- (void)setupNavigation {
    
    [self.navigationController setNavigationBarHidden:YES];
    
    self.topMarginConstraint.constant = self.navH;
    
    self.view.backgroundColor = getColorFromString(@"F5F5F5");
    
    self.navigationBarView.titleLabel.text = @"找回密码";
}

- (void)setupUI {
    
    [self setupGetCodeBtn];
    
    [self setupTextField];
}

- (void)setupGetCodeBtn {
    
    [self.getCodeBtn setBackgroundImage:getImageFromName(@"btn_orange_select") forState:UIControlStateNormal];
    [self.getCodeBtn setTitleColor:kColorWhite() forState:UIControlStateNormal];
    
    [self.getCodeBtn setBackgroundImage:getImageFromName(@"btn_orange_normal") forState:UIControlStateDisabled];
    [self.getCodeBtn setTitleColor:getColorFromString(@"#FF6816") forState:UIControlStateDisabled];
}

- (void)setupTextField {
    
    self.phoneNumTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.codeTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.passWordTextField.keyboardType = UIKeyboardTypeASCIICapable;
    self.secondPassWordTextField.keyboardType = UIKeyboardTypeASCIICapable;
    
    self.phoneNumTextField.tag = kPhoneNumTextFieldTag;
    self.codeTextField.tag = kCodeTextFieldTag;
    self.passWordTextField.tag = kNewPassWordTextFieldTag;
    self.secondPassWordTextField.tag = kSecondPassWordTextFieldTag;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
}

#pragma private
- (void)setupTimer {
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    [self.timer fire];
}

- (void)removeTimer {
    
    [self.timer invalidate];
    self.timer = nil;
}

#pragma mark - touchAction
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.view endEditing:YES];
}

- (IBAction)getCodeBtnDidClick:(UIButton *)sender {
    
    if ([NRWCarRegularTool isPhoneNum:self.phoneNumTextField.text]) {
        
        [self loadCode];
        
    } else {
        
        [ShowMessage showHintMessage:@"请输入正确的手机号码" duration:2 withRemindId:remindWarning];
    }
}

- (IBAction)completedBtnDidClick:(UIButton *)sender {
    
    if ([self.passWordTextField.text isEqualToString:self.secondPassWordTextField.text]) {
        
        [self loadSave];
    } else {
        
        [ShowMessage showHintMessage:@"两次密码输入不一致, 请重新输入密码" duration:2 withRemindId:remindWarning];
    }
}

#pragma mark - UITextFieldDelegate
- (void)textFieldTextDidChange:(NSNotification *)notification {
    
    UITextField *textField = notification.object;
    
    if (textField.tag == kPhoneNumTextFieldTag) {
        
        if (textField.text.length > 11) {
            
            self.phoneNumTextField.text = [self.phoneNumTextField.text substringToIndex:11];
        }
    }
    
    if (textField.tag == kCodeTextFieldTag) {
        
        if (self.codeTextField.text.length > 6) {
            
            self.codeTextField.text = [self.codeTextField.text substringToIndex:6];
        }
    }
    
    if (textField.tag == kNewPassWordTextFieldTag) {
        
        if (self.passWordTextField.text.length > 16) {
            
            self.passWordTextField.text = [self.passWordTextField.text substringToIndex:16];
        }
    }
    
    if (textField.tag == kSecondPassWordTextFieldTag) {
        
        if (self.secondPassWordTextField.text.length > 16) {
            
            self.secondPassWordTextField.text = [self.secondPassWordTextField.text substringToIndex:16];
        }
    }
    
    if (self.phoneNumTextField.text.length == 11 &&
        self.codeTextField.text.length == 6 &&
        self.passWordTextField.text.length >= 6 &&
        self.passWordTextField.text.length <= 16 &&
        self.secondPassWordTextField.text.length >= 6 &&
        self.secondPassWordTextField.text.length <= 16) {
        
        self.completedBtn.enabled = YES;
    } else {
        self.completedBtn.enabled = NO;
    }
}

#pragma mark - network
- (void)loadCode {
    
    NSString *url = [NSString stringWithFormat:@"%@%@", Api, getSmsValidateCode];
    
    [SVProgressHUD show];
    
    [YQNetworking getWithUrl:url refreshRequest:NO cache:NO params:@{@"userMobile": self.phoneNumTextField.text} progressBlock:nil successBlock:^(id response) {
        
        [SVProgressHUD dismiss];
        
        if ([response[@"code"] integerValue] == 1) {
            
            self.getCodeBtn.enabled = NO;
            [self setupTimer];
            [ShowMessage showHintMessage:@"发送成功" duration:1 withRemindId:remindSuccess];
        } else {
            
            [ShowMessage showHintMessage:response[@"msg"] duration:2 withRemindId:remindWarning];
        }
        
    } failBlock:^(NSError *error) {
        [ShowMessage showHintMessage:@"请求失败, 请稍后再试" duration:2 withRemindId:remindFail];
        [SVProgressHUD dismiss];
    }];
}

- (void)loadSave {
    
    NSString *url = [NSString stringWithFormat:@"%@%@", Api, findPwd];
    
    NSDictionary *dict = @{
                           @"newPassword": self.passWordTextField.text,
                           @"userMobile": self.phoneNumTextField.text,
                           @"validateCode": self.codeTextField.text
                           };
    
    [SVProgressHUD show];
    
    [YQNetworking postWithUrl:url refreshRequest:NO cache:NO params:dict progressBlock:nil successBlock:^(id response) {
    
        [SVProgressHUD dismiss];
        
        if ([response[@"code"] integerValue] == 1) {
            
            [ShowMessage showHintMessage:@"找回密码成功" duration:2 withRemindId:remindSuccess];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        } else {
            
            [ShowMessage showHintMessage:response[@"msg"] duration:2 withRemindId:remindWarning];
        }
        
    } failBlock:^(NSError *error) {
        
        [ShowMessage showHintMessage:@"请求失败, 请稍后再试" duration:2 withRemindId:remindWarning];
        [SVProgressHUD dismiss];
    }];
}

#pragma mark - timerAction
- (void)timerAction:(NSTimer *)timer {
    
    if (_timeLeft == 1) {
        self.getCodeBtn.enabled = YES;
        [self removeTimer];
        return;
    }
    _timeLeft--;
    [self.getCodeBtn setTitle:[NSString stringWithFormat:@"%zd秒", _timeLeft] forState:UIControlStateDisabled];
}

@end
